package com.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.meeting.dto.LoginDTO;
import com.meeting.dto.RegisterDTO;
import com.meeting.dto.UserQueryDTO;
import com.meeting.dto.UserStatusDTO;
import com.meeting.vo.CustomerVO;
import com.meeting.vo.PageResult;
import com.meeting.vo.Result;
import com.meeting.entity.Customer;
import com.meeting.mapper.CustomerMapper;
import com.meeting.service.CustomerService;
import com.meeting.utils.JWTUtil;
import com.meeting.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public Result login(LoginDTO loginDTO) {
        Customer customer = customerMapper.getByUsername(loginDTO.getUsername());
        if (customer == null || !customer.getPassword().equals(loginDTO.getPassword())) {
            return Result.error("用户名或密码错误");
        }
        if (customer.getStatus() == 0) {
            return Result.error("账户被冻结，请联系管理员");
        }
        if (customer.getStatus() == 2) {
            return Result.error("账户尚未审核通过，请联系管理员");
        }
        String token = JWTUtil.generateToken(customer.getId(), "customer");
        LoginVO vo = new LoginVO();
        vo.setName(customer.getName());
        vo.setToken(token);
        vo.setUsername(customer.getUsername());
        vo.setCompany(customer.getCompany());
        vo.setPhone(customer.getPhone());

        return Result.success(vo);
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
        //1.用户是否存在
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customer::getUsername,registerDTO.getUsername());
        Customer existingCustomer = customerMapper.selectOne(wrapper);
        if(existingCustomer!=null){
            return Result.error("该用户名已存在");
        }

        if(!isValidPhoneNumber(registerDTO.getPhone())){
            return Result.error("手机号格式不正确");
        }

        LambdaQueryWrapper<Customer> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Customer::getPhone,registerDTO.getPhone());
        existingCustomer = customerMapper.selectOne(wrapper1);
        if(existingCustomer!=null){
            return Result.error("该电话已存在");
        }

        Customer customer = new Customer();
        BeanUtils.copyProperties(registerDTO,customer);
        customer.setStatus(2); //等待审核
        customerMapper.insert(customer);
        return Result.success("注册成功，请耐心等待审核");
    }

    private boolean isValidPhoneNumber(String phone) {
        // 简单的手机号验证，假设手机号为11位数字，以1开头
        return phone != null && phone.matches("^1\\d{10}$");
    }

    // 新增：客户登出实现
    @Override
    public Result logout() {
        try {
            log.info("客户登出成功");
            return Result.success("登出成功");
        } catch (Exception e) {
            log.error("客户登出失败", e);
            return Result.error("登出失败");
        }
    }

    @Override
    public PageResult<CustomerVO> listCustomers(UserQueryDTO userQueryDTO) {
        try {
            log.info("分页查询客户列表：{}", userQueryDTO);
            
            // 构建查询条件
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (StringUtils.hasText(userQueryDTO.getUsername())) {
                queryWrapper.like(Customer::getUsername, userQueryDTO.getUsername());
            }
            
            if (StringUtils.hasText(userQueryDTO.getName())) {
                queryWrapper.like(Customer::getName, userQueryDTO.getName());
            }
            
            if (StringUtils.hasText(userQueryDTO.getPhone())) {
                queryWrapper.like(Customer::getPhone, userQueryDTO.getPhone());
            }
            
            if (StringUtils.hasText(userQueryDTO.getCompany())) {
                queryWrapper.like(Customer::getCompany, userQueryDTO.getCompany());
            }
            
            if (userQueryDTO.getStatus() != null) {
                queryWrapper.eq(Customer::getStatus, userQueryDTO.getStatus());
            }
            
            // 分页查询
            PageHelper.startPage(userQueryDTO.getPage(), userQueryDTO.getPageSize());
            Page<Customer> page = (Page<Customer>) customerMapper.selectList(queryWrapper);
            
            // 转换为VO
            List<CustomerVO> customerVOList = new ArrayList<>();
            for (Customer customer : page.getResult()) {
                CustomerVO customerVO = new CustomerVO();
                BeanUtils.copyProperties(customer, customerVO);
                
                // 设置状态文本
                switch (customer.getStatus()) {
                    case 0:
                        customerVO.setStatusText("已冻结");
                        break;
                    case 1:
                        customerVO.setStatusText("已启用");
                        break;
                    case 2:
                        customerVO.setStatusText("待审核");
                        break;
                    default:
                        customerVO.setStatusText("未知");
                }
                
                customerVOList.add(customerVO);
            }
            
            return new PageResult<>(page.getTotal(), customerVOList);
        } catch (Exception e) {
            log.error("分页查询客户列表失败", e);
            return new PageResult<>(0L, new ArrayList<>());
        }
    }

    @Override
    public boolean updateStatus(UserStatusDTO userStatusDTO) {
        try {
            log.info("更新客户状态：{}", userStatusDTO);
            
            // 检查客户是否存在
            Customer customer = customerMapper.selectById(userStatusDTO.getId());
            if (customer == null) {
                log.error("客户不存在，ID：{}", userStatusDTO.getId());
                return false;
            }
            
            // 检查状态值是否合法
            Integer status = userStatusDTO.getStatus();
            if (status != 0 && status != 1 && status != 2) {
                log.error("状态值不合法，状态：{}", status);
                return false;
            }
            
            // 更新状态
            Customer updateCustomer = new Customer();
            updateCustomer.setId(userStatusDTO.getId());
            updateCustomer.setStatus(userStatusDTO.getStatus());
            int result = customerMapper.updateById(updateCustomer);
            
            return result > 0;
        } catch (Exception e) {
            log.error("更新客户状态失败", e);
            return false;
        }
    }

    @Override
    public CustomerVO getCustomerDetail(Integer id) {
        try {
            log.info("获取客户详情，ID：{}", id);
            
            Customer customer = customerMapper.selectById(id);
            if (customer == null) {
                log.error("客户不存在，ID：{}", id);
                return null;
            }
            
            CustomerVO customerVO = new CustomerVO();
            BeanUtils.copyProperties(customer, customerVO);
            
            // 设置状态文本
            switch (customer.getStatus()) {
                case 0:
                    customerVO.setStatusText("已冻结");
                    break;
                case 1:
                    customerVO.setStatusText("已启用");
                    break;
                case 2:
                    customerVO.setStatusText("待审核");
                    break;
                default:
                    customerVO.setStatusText("未知");
            }
            
            return customerVO;
        } catch (Exception e) {
            log.error("获取客户详情失败", e);
            return null;
        }
    }
}